package com.qy.controller.manage;

import com.github.pagehelper.PageHelper;
import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.ExcelUtil.ExcelLogs;
import com.qy.base.utils.ExcelUtil.ExcelUtil;
import com.qy.base.utils.UploadFile;
import com.qy.model.Charge;
import com.qy.model.Policy;
import com.qy.model.Unit;
import com.qy.service.AdminService;
import com.qy.service.ChargeService;
import com.qy.service.PolicyService;
import com.qy.service.UnitService;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController("Manage-PolicyController")
@RequestMapping("/manage/policy")
public class PolicyController {
    @Resource
    private PolicyService policyService;

    @Resource
    private UnitService unitService;

    @Resource
    private ChargeService chargeService;

    //新增政策
    @PostMapping("/add")
    public Result add(@RequestBody Policy policy) {
        if (policy.getPolicy_name() == null || policy.getPolicy_name().isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        List<Policy> policyList = policyService.selectPolicyByName(policy);
        if (policyList.size() == 0) {
            policy.setPublisher("平台");
            policy.setAdd_time(String.valueOf(new Date().getTime()));
            policyService.save(policy);
            return ResultGenerator.successResult();
        } else {
            throw new ServiceException(Constants.CODE_EXIST_POLICY);
        }

    }

    //删除政策
    @PostMapping("/delete")
    public Result delete(@RequestBody Policy policy) {
        if (policy.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        policyService.deletePolicy(policy);
        return ResultGenerator.successResult();
    }

    //    政策列表-编辑
    @PostMapping("/update")
    public Result update(@RequestBody Policy policy) {
        if (policy.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        List<Policy> policyList = policyService.selectPolicyByName(policy);
        if (policyList.size() != 0) {
            if (!policy.getId().equals(policyList.get(0).getId())) {
                throw new ServiceException(Constants.CODE_EXIST_POLICY);
            }
        }
        policyService.update(policy);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Policy policy = policyService.findById(id);
        return ResultGenerator.successResult(policy);
    }

    @GetMapping("/list")
    public Result list(PageBean<Policy> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Policy> list = policyService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //   政策库-政策列表
    @GetMapping("/policyList")
    public Result policyList(PageBean<Map> page, Integer type, String content, Policy policy) {
        if (type == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        } else if (type == 1) {
            policy.setPolicy_name(content);
        } else if (type == 2) {
            policy.setPublisher(content);
        }
        PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
        List<Map> list = policyService.managePolicyList(policy);
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //   政策列表-查看政策
    @GetMapping("/seePolicy")
    public Result seePolicy(Integer id) {
        if (id == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Map<String, Object> map = new HashMap<>();
        List<Unit> unitList = new ArrayList<>();
        List<Charge> chargeList = new ArrayList<>();
        Policy policy = policyService.seePolicy(id);
        if (policy.getUnit_ids() != null && !policy.getUnit_ids().equals("") ){
           unitList = unitService.findByIds(policy.getUnit_ids());
        }
        if (policy.getCharge_ids() != null &&!policy.getCharge_ids().equals("") ){
            chargeList = chargeService.findByIds(policy.getCharge_ids());
        }

//        String[] unitIds = policy.getUnit_ids().split(",");
//        String[] unitsName = new String[]{};
//        if (unitIds.length != 0){
//            for (String unitId : unitIds){
//                int unitid = Integer.parseInt(unitId);
//                Unit unit = new Unit();
//                unitService.findById(unitid);
//            }
//        }

        map.put("policy",policy);
        map.put("unitList", unitList);
        map.put("chargeList", chargeList);

        return ResultGenerator.successResult(map);
    }

    //政策上下架
    @PostMapping("/policyState")
    public Result policyState(@RequestBody Policy policy) {
        if (policy.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        policyService.policyState(policy);
        return ResultGenerator.successResult();
    }

    //导入
    @PostMapping("/Import")
    public Result Import(@RequestBody Policy policy) throws Exception {
        String fileUrl = null;
        if (policy.getExcel() != null && !policy.getExcel().isEmpty()) {
            fileUrl = UploadFile.uploadBase64(policy.getExcel());
        } else {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }

        File f = new File("../" + fileUrl);
        InputStream inputStream = new FileInputStream(f);

        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);

        if (importExcel.size() != 0) {
            for (Map m : importExcel) {
                Policy policy1 = new Policy();
                policy1.setPolicy_name(m.get("政策名称").toString());
                if (m.get("发布单位") != null && !m.get("发布单位").toString().isEmpty()) {
                    policy1.setRelease_unit(m.get("发布单位").toString());
                }
                policy1.setProvince(m.get("所在省份（由所在地区拆分而来）").toString());
                if (m.get("所在地市（由所在地区拆分而来）") != null && !m.get("所在地市（由所在地区拆分而来）").toString().isEmpty()) {
                    policy1.setCity(m.get("所在地市（由所在地区拆分而来）").toString());
                }

                if (m.get("所在区县（由所在地区拆分而来）") != null && !m.get("所在区县（由所在地区拆分而来）").toString().isEmpty()) {
                    policy1.setCounty(m.get("所在区县（由所在地区拆分而来）").toString());
                }
                if (m.get("补贴金额") != null && !m.get("补贴金额").toString().isEmpty()) {
                    policy1.setSubsidies(m.get("补贴金额").toString());
                }
                if (m.get("其他扶持") != null && !m.get("其他扶持").toString().isEmpty()) {
                    policy1.setOther_support(m.get("其他扶持").toString());
                }
                if (m.get("发布人") != null && !m.get("发布人").toString().isEmpty()) {
                    policy1.setPublisher(m.get("发布人").toString());
                }else {
                    policy1.setPublisher("平台");
                }

                if (m.get("联系方式") != null && !m.get("联系方式").toString().isEmpty()) {
                    policy1.setPolicy_tel(m.get("联系方式").toString());
                }
                if (m.get("报名条件") != null && !m.get("报名条件").toString().isEmpty()) {
                    policy1.setSign_condition(m.get("报名条件").toString());

                }
//                policy1.setSign_condition(m.get("报名条件").toString());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                if (m.get("报名时间（年/月/日）") != null && !m.get("报名时间（年/月/日）").toString().isEmpty()) {
//                    Date date1 = null;
//                    date1 = sdf.parse(m.get("报名时间（年/月/日）").toString());
//                    Long sign_time = date1.getTime();
                    policy1.setAudit_time(m.get("报名时间（年/月/日）").toString());
                }

                if (m.get("审核流程") != null && !m.get("审核流程").toString().isEmpty()) {
                    policy1.setAudit_process(m.get("审核流程").toString());
                }

                if (m.get("审核时间（年/月/日）") != null && !m.get("审核时间（年/月/日）").toString().isEmpty()) {
//                    Date date2 = null;
//                    date2 = sdf.parse(m.get("审核时间（年/月/日）").toString());
//                    Long audit_time = date2.getTime();
                    policy1.setAudit_time(m.get("审核时间（年/月/日）").toString());
                }

                if (m.get("是否直营") != null && !m.get("是否直营").toString().isEmpty()) {
                    if (m.get("是否直营").toString().equals("直营")) {
                        policy1.setDirect_sale(1);
                    } else if (m.get("是否直营").toString().equals("非直营")) {
                        policy1.setDirect_sale(2);
                    }
                }
                List<Policy> list = policyService.selectPolicyByName(policy1);
                if (list.size() == 0) {
                    policy1.setPolicy_type(1);
                    policy1.setAdd_time(DateUtil.getNowTimestamp());
                    policyService.save(policy1);
                } else {
                    throw new ServiceException(Constants.CODE_EXIST_POLICY);
                }
            }
        } else {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        return ResultGenerator.successResult();
    }
}
